package com.b2b.controller;

import com.alibaba.fastjson.JSON;
import com.b2b.exception.CustomException;
import com.b2b.exception.CustomUnauthorizedException;

import com.b2b.model.ShopDto;
import com.b2b.model.common.ResponseBean;

import com.b2b.model.receive.BriefGood;
import com.b2b.model.receive.ShopSearch;
import com.b2b.service.ShopService;
import com.b2b.util.GoodsUtil;
import com.b2b.util.ShopUtil;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/shop")
@PropertySource("classpath:config.properties")
public class ShopController {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;//client;
    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;

    private final ShopUtil shopUtil;
    private final GoodsUtil goodsUtil;

    private final ShopService shopService;
    @Autowired
    public ShopController(ShopUtil shopUtil,ShopService iShopService,GoodsUtil goodsUtil){
        this.shopUtil=shopUtil;
        this.shopService =iShopService;
        this.goodsUtil = goodsUtil;
    }

    /**
     * 新增店铺信息
     * @param shopDto
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     * @date 2018/8/30 10:42
     */
    @PostMapping("/add")
//    @RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
    public ResponseBean add(@RequestBody ShopDto shopDto) throws IOException {
        shopDto.setEvaluate(0.0);
        shopDto.setSatisfactionRate(0);
        shopDto.setComplaintRate(0);
        // 判断当前帐号是否存在
        ShopDto shopDtoTemp = new ShopDto();
        shopDtoTemp.setShopName(shopDto.getShopName());
        char state = '0';
        shopDtoTemp = shopService.selectOne(shopDtoTemp);
        if (shopDtoTemp != null ) {
            throw new CustomUnauthorizedException("该店铺名称已存在(Account exist.)");
        }
        shopDto.setState(state);
        int count = shopService.insert(shopDto);
        if (count <= 0) {
            throw new CustomException("新增失败(Insert Failure)");
        }else {
            IndexRequest request = new IndexRequest("shop");
            Integer id = shopDto.getShopId();
            request.timeout(TimeValue.timeValueSeconds(3));
            request.id(""+id);
            //数据封入请求
            IndexRequest source = request.source(JSON.toJSONString(shopDto), XContentType.JSON);
            //客户端发送请求  获取响应结果
            client.index(request, RequestOptions.DEFAULT);
        }
        return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", null);
    }

    /**
     * 获取指定店铺信息
     * @param shopSearch
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     * @date 2018/8/30 10:42
     */
    @GetMapping("/search")
    //@RequiresPermissions(logical = Logical.AND, value = {"user:view"})
    public ResponseBean findByKeyword(ShopSearch shopSearch) throws IOException {
        Integer pageNo = shopSearch.getPage();
        Integer pageSize= shopSearch.getRows();
        SearchRequest searchRequest = new SearchRequest("shop");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (null != shopSearch.getKeyWord()){
            boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("shopName", shopSearch.getKeyWord()));
            boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("goodsType",shopSearch.getKeyWord()));
        }else {
            throw new CustomException("查询失败(Query Failure)");
        }
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String,Object>> shopList = new ArrayList<>();
        for (SearchHit documentFields : search.getHits()){
            Map<String,Object> shop = documentFields.getSourceAsMap();
            Integer shopId = Integer.parseInt(String.valueOf(shop.get("shopId")));
            List<BriefGood> briefGoodList = goodsUtil.getBriefGood(shopId);
            shop.put("goodsList",briefGoodList);
            shopList.add(shop);
        }
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", shopList);
    }


    @GetMapping("/getMy")
    public ResponseBean getByCompanyId(@RequestParam Integer companyId){
        ShopDto shopDtoTemp = new ShopDto();
        shopDtoTemp.setCompanyId(companyId);
        List<ShopDto> shopDtos = shopService.select(shopDtoTemp);
        if (shopDtos == null) {
            throw new CustomException("查询失败(Query Failure)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", shopDtos);
    }

    @GetMapping("/getDetail")
    public ResponseBean getByShopId(@RequestParam Integer shopId){
        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(shopId);
        if (shopService.selectCount(shopDto)<=0){
            throw new CustomException("查询失败(Query Failure)");
        }
        shopDto = shopService.selectByPrimaryKey(shopId);
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", shopDto);
    }
    /**
     * 更新商店信息
     * @param shopDto
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     * @date 2018/8/30 10:42
     */
    @PutMapping
    //@RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
    public ResponseBean update( @RequestBody ShopDto shopDto) throws IOException {
        // 查询数据库
        ShopDto shopDtoTemp = new ShopDto();
        shopDtoTemp.setShopId(shopDto.getShopId());
        shopDtoTemp = shopService.selectOne(shopDtoTemp);
        if (shopDtoTemp == null) {
            throw new CustomUnauthorizedException("该帐号不存在(Account not exist.)");
        }else {
            shopDto.setShopId(shopDtoTemp.getShopId());
        }
        int count = shopService.updateByPrimaryKeySelective(shopDto);
        if (count <= 0) {
            throw new CustomException("更新失败(Update Failure)");
        }else {
            UpdateRequest updateRequest = new UpdateRequest("shop", ""+shopDto.getShopId());
            updateRequest.timeout("3s");
            UpdateRequest doc = updateRequest.doc(JSON.toJSONString(shopDto), XContentType.JSON);
            client.update(doc, RequestOptions.DEFAULT);
        }
        return new ResponseBean(HttpStatus.OK.value(), "更新成功(Update Success)", shopDto);
    }



    /**
     * 删除相关企业信息
     * @param shopDto
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     * @date 2018/8/30 10:43
     */
    @DeleteMapping
    // @RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
    public ResponseBean delete(@RequestBody ShopDto shopDto) throws IOException {
        Integer id = shopDto.getShopId();
        int count = shopService.deleteByPrimaryKey(id);
        if (count <= 0) {
            throw new CustomException("删除失败，ID不存在(Deletion Failed. ID does not exist.)");
        }else {
            DeleteRequest deleteRequest = new DeleteRequest("shop", ""+id);
            deleteRequest.timeout("3s");
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        }
        return new ResponseBean(HttpStatus.OK.value(), "删除成功(Delete Success)", null);
    }




}
